package com.softWang.common.dataPermission.rule;

import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.softWang.common.dataPermission.aop.DataPermission;
import com.softWang.common.dataPermission.context.DataPermissionContextHolder;
import lombok.RequiredArgsConstructor;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 默认的 DataPermissionRuleFactoryImpl 实现类
 * 支持通过 {@link DataPermissionContextHolder} 过滤数据权限
 */
@RequiredArgsConstructor
public class DataPermissionRuleFactoryImpl implements DataPermissionRuleFactory {

    /**
     * 数据权限规则数组
     */
    private final List<DataPermissionRule> rules;

    @Override
    public List<DataPermissionRule> getDataPermissionRules() {
        return rules;
    }

    @Override // mappedStatementId 参数，暂时没有用。以后，可以基于 mappedStatementId + DataPermission 进行缓存
    public List<DataPermissionRule> getDataPermissionRule(String tableName,String mappedStatementId) {
        // 1. 无数据权限规则
        if (rules == null || rules.isEmpty()) {
            return Collections.emptyList();
        }
        // 2. 未配置，则默认开启
        DataPermission dataPermission = DataPermissionContextHolder.get();
        if (dataPermission == null) {
            return rules;
        }
        // 4. 已配置，只选择部分规则
        if (dataPermission.includeRules() != null && dataPermission.includeRules().length > 0) {
            List includeRules = Arrays.asList(dataPermission.includeRules());
            return rules.stream().filter(rule -> includeRules.contains(rule.getClass()))
                    .collect(Collectors.toList()); // 一般规则不会太多，所以不采用 HashSet 查询
        }
        // 5. 已配置，只排除部分规则
        if (dataPermission.excludeRules() != null && dataPermission.excludeRules().length > 0) {
            List excludeRules = Arrays.asList(dataPermission.excludeRules());
            return rules.stream().filter(rule -> !excludeRules.contains(rule.getClass()))
                    .collect(Collectors.toList()); // 一般规则不会太多，所以不采用 HashSet 查询
        }
        // 6. 已配置，全部规则
        return rules;
    }


}
